package com.bittech.client.service;

import com.bittech.util.CommUtil;
import com.bittech.vo.GroupChatVO;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.PrintStream;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: yuisama
 * @Date: 2019-06-12 16:52
 * @Description:
 */
public class UserFriendsList {
    private String myName;
    private JPanel userFriendsList;
    // 好友滚动列表
    private JScrollPane friendsPanel;
    // 好友群滚动列表
    private JScrollPane groupChatPanel;
    private JButton createGroupBtn;
    // 私聊界面缓存
    private Map<String,ChatGUI> friendsChatGUIList = new HashMap<>();
    // 群聊界面缓存
    private Map<String,GroupChatGUI> groupChatGUIList = new HashMap<>();
    // 所有在线好友
    private List<String> nameList;
    // 所有群聊名称以及群成员姓名
    private Map<String,List<String>> groupChatMap = new HashMap<>();
    private Connect2Server connect2Server;
    // 点击标签开始私聊事件
    private class MouseAda implements MouseListener {
        // 私聊客户端名称
        private String labelName;

        public MouseAda(String labelName) {
            this.labelName = labelName;
        }

        @Override
        public void mouseClicked(MouseEvent e) {
             // 发起私聊
             if (friendsChatGUIList.containsKey(labelName)) {
                 ChatGUI chatGUI = friendsChatGUIList.get(labelName);
                 chatGUI.getFrame().setVisible(true);
             }else {
                 ChatGUI chatGUI = new ChatGUI(labelName, myName, connect2Server);
                 friendsChatGUIList.put(labelName,chatGUI);
             }
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
    // 点击标签开始群聊事件
    private class GroupLabelEvent implements MouseListener {
        private String myName;
        private String groupChatName;
        private List<String> membersName;

        public GroupLabelEvent(String myName, String groupChatName, List<String> membersName) {
            this.myName = myName;
            this.groupChatName = groupChatName;
            this.membersName = membersName;
        }

        /**
         * 唤起群聊界面
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            if (groupChatGUIList.containsKey(groupChatName)) {
                GroupChatGUI groupChatGUI = groupChatGUIList.get(groupChatName);
                groupChatGUI.getFrame().setVisible(true);
            }
            GroupChatGUI groupChatGUI = new GroupChatGUI(groupChatName,membersName,myName,connect2Server);
            groupChatGUIList.put(groupChatName,groupChatGUI);
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }

    private class ReloadFriendList implements Runnable {
        private Scanner in = new Scanner(connect2Server.getClientRead());
        @Override
        public void run() {
            while (true) {
                if (in.hasNextLine()) {
                    String command = in.nextLine();
                    // 有新好友上线
                    if (command.startsWith("newReload")) {
                        String userName = command.split(":")[1];
                        JOptionPane.showMessageDialog(null,"好友"
                                +userName+"已经上线!","提示",
                                JOptionPane.INFORMATION_MESSAGE);
                        nameList.add(userName);
                        refreshList();
                    }
                    // 有好友下线
                    if (command.startsWith("delReload")) {

                    }
                    // 私聊流程
                    if (command.startsWith("P:")) {
                        // 弹出私聊界面
                        // P:yang2dog_yang66-hey i am yang66
                        String myName = command.split(":")[1].split("_")[0];
                        String otherName = command.split(":")[1].split("_")[1].split("-")[0];
                        String msg = otherName + "说:"+command.split(":")[1].split("-")[1];
                        if (friendsChatGUIList.containsKey(otherName)) {
                            ChatGUI chatGUI = friendsChatGUIList.get(otherName);
                            chatGUI.readFromServer(msg);
                        }else {
                            ChatGUI chatGUI = new ChatGUI(otherName, myName, connect2Server);
                            friendsChatGUIList.put(otherName,chatGUI);
                            chatGUI.readFromServer(msg);
                        }
                    }
                    if (command.startsWith("G:")) {
                        // 弹出群聊界面
                        // G:{"groupName":"群聊1","membersName":["yang2dog","yuisama","yang66"]}
                        // _yuisama-hello I am yuisama
                        String jsonStr = command.substring(2).split("_")[0];
                        GroupChatVO groupChatVO =
                                (GroupChatVO) CommUtil.json2Object(jsonStr,GroupChatVO.class);
                        String useFulStr = command.split("_")[1];
                        // yuisama-hello I am yuisama
                        String senderName = useFulStr.split("-")[0];
                        String groupName = groupChatVO.getGroupName();
                        String msg = senderName + "说:"+useFulStr.split("-")[1];
                        if(groupChatGUIList.containsKey(groupName)) {
                            GroupChatGUI groupChatGUI = groupChatGUIList.get(groupName);
                            groupChatGUI.readFromServer(msg);
                        }else {
                            GroupChatGUI groupChatGUI = new GroupChatGUI(groupName,groupChatVO.getMembersName(),
                                    myName,connect2Server);
                            // 刷新好友列表界面
                            groupChatMap.put(groupName,groupChatVO.getMembersName());
                            refreshGroupList();
                            // 刷新群聊界面缓存
                            groupChatGUIList.put(groupName,groupChatGUI);
                            groupChatGUI.readFromServer(msg);
                        }
                    }
                }
            }
        }
    }

    public UserFriendsList(List<String> nameList,String clientName,Connect2Server connect2Server) {
        this.connect2Server = connect2Server;
        this.myName = clientName;
        JFrame frame = new JFrame(clientName);
        frame.setContentPane(userFriendsList);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(400,300);
        frame.setVisible(true);
        SwingUtilities.updateComponentTreeUI(frame);
        this.nameList = nameList;
        // 刷新好友列表
        refreshList();
        // 启动后台线程检测是否有新的好友上线，刷新好友列表并发通知
        Thread listThread = new Thread(new ReloadFriendList());
        listThread.setDaemon(true);
        listThread.start();

        // 创建群聊事件
        createGroupBtn.addActionListener( (e) -> {
            // 主panel
            JPanel chooseGroupMainPanel = new JPanel();
            chooseGroupMainPanel.setLayout(new BoxLayout(chooseGroupMainPanel
                    ,BoxLayout.Y_AXIS));
            // 存放所有复选框
            JPanel checkBoxPanel = new JPanel();
            checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel,BoxLayout.Y_AXIS));
            for (int i = 0;i < nameList.size();i++) {
                JCheckBox checkBox = new JCheckBox(nameList.get(i));
                checkBoxPanel.add(checkBox);
            }
            // 存放群名输入框
            JPanel groupNamePanel = new JPanel();
            JLabel label = new JLabel("请输入群名");
            label.setAlignmentX(Component.LEFT_ALIGNMENT);
            JTextField inputNameTextField = new JTextField(8);
            inputNameTextField.setAlignmentX(Component.RIGHT_ALIGNMENT);
            groupNamePanel.add(label);
            groupNamePanel.add(inputNameTextField);
            // 存放提交按钮
            JButton confirmBtn = new JButton("确认选择");
            confirmBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
            // 获取所有选择的好友名称
            AtomicReference<String> groupName = new AtomicReference<>();
            List<String> choseFriends = new ArrayList<>();
            chooseGroupMainPanel.add(checkBoxPanel);
            chooseGroupMainPanel.add(groupNamePanel);
            chooseGroupMainPanel.add(confirmBtn);
            JFrame newFrame = new JFrame("创建群聊");
            newFrame.setContentPane(chooseGroupMainPanel);
            newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            newFrame.setSize(300,300);
            newFrame.setLocationRelativeTo(null);
            newFrame.setVisible(true);
            // 确认事件
            confirmBtn.addActionListener((event) -> {
                Component[] components = checkBoxPanel.getComponents();
                for (Component component : components) {
                    JCheckBox checkBox = (JCheckBox) component;
                    if (checkBox.isSelected())
                        choseFriends.add(checkBox.getText());
                }
                choseFriends.add(myName);
                // 获取输入的群名
                groupName.set(inputNameTextField.getText());
                String name = groupName.get();
                System.out.println("选择的好友为"+choseFriends);
                System.out.println("群名为:"+name);
                groupChatMap.put(name,choseFriends);
                refreshGroupList();
                PrintStream send2Server = new PrintStream(connect2Server.getClientWrite()
                        ,true);
                GroupChatVO groupChatVO = new GroupChatVO();
                groupChatVO.setGroupName(name);
                groupChatVO.setMembersName(choseFriends);
                String str2Server = "R:" + CommUtil.object2Json(groupChatVO);
                System.out.println("向服务器发送群聊注册信息为:"+str2Server);
                send2Server.println(str2Server);
                newFrame.setVisible(false);
            });

        });
    }

    public void setNameList(List<String> nameList) {
        this.nameList = nameList;
    }

    /**
     * 刷新好友列表方法
     */
    public void refreshList() {
        int friendSize = this.nameList.size();
        JLabel[] friendsLabels = new JLabel[friendSize];
        JPanel friendsPanel = new JPanel();
        friendsPanel.setLayout(new BoxLayout(friendsPanel, BoxLayout.Y_AXIS));
        for (int i = 0;i < friendSize;i++) {
            friendsLabels[i] = new JLabel(nameList.get(i));
            friendsLabels[i].setBounds(new Rectangle(51, 30, 131, 20));
            friendsLabels[i].addMouseListener(new MouseAda(friendsLabels[i].getText()));
        }
        for (int i = 0;i < friendSize;i++) {
            friendsPanel.add(friendsLabels[i]);
            friendsLabels[i].setVisible(true);
        }
        this.friendsPanel.setViewportView(friendsPanel);
        this.friendsPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        this.friendsPanel.revalidate();
        userFriendsList.revalidate();
    }

    public void refreshGroupList() {
        int groupSize = this.groupChatMap.size();
        JLabel[] groupLabels = new JLabel[groupSize];
        // 存储所有群聊标签Panel
        JPanel groupPanel = new JPanel();
        groupPanel.setLayout(new BoxLayout(groupPanel, BoxLayout.Y_AXIS));
        Set<Map.Entry<String,List<String>>> set = groupChatMap.entrySet();
        Iterator<Map.Entry<String,List<String>>> iterator = set.iterator();
        for (int i = 0;i < groupSize;i++) {
            String labelName = "";
            List<String> membersName = null;
            if (iterator.hasNext()) {
                Map.Entry<String,List<String>> entry = iterator.next();
                labelName = entry.getKey();
                membersName = entry.getValue();
            }
            groupLabels[i] = new JLabel(labelName);
            groupLabels[i].setBounds(new Rectangle(51, 30, 131, 20));
            groupLabels[i].addMouseListener(new GroupLabelEvent(myName,labelName,membersName));
        }
        for (int i = 0;i < groupSize;i++) {
            groupPanel.add(groupLabels[i]);
        }
        groupChatPanel.setViewportView(groupPanel);
        groupChatPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        groupChatPanel.revalidate();
        userFriendsList.revalidate();
    }
}
